package com.dongdongshop.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class MailUtil {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.sender.from}")
    String from;
    public void sendSimpleMail(String to, String subject, String content) {
        // new一个简单邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置发件人
        message.setFrom(from);
        // 设置收件人
        message.setTo(to);
        // 设置主题
        message.setSubject(subject);
        // 内容
        message.setText(content);
        javaMailSender.send(message);
    }

    // 发送带附件的邮件
    public void sendAttachmentsMail(String to, String subject, String content, String filePath)
            throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper helper =
                new MimeMessageHelper(message, true);

        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content);

        File file = new File(filePath);
        // 获取文件名称
        String fileName = file.getName();
        helper.addAttachment(fileName, file);
        javaMailSender.send(message);
    }
}